import 'reflect-metadata';
import { initializeDatabase } from '@weubi/shared';
import { CrawlerService } from './services/CrawlerService';
import { QueueProcessor } from './processors/QueueProcessor';
import { SchedulerService } from './schedulers/SchedulerService';
import { logger } from './utils/logger';
import * as dotenv from 'dotenv';

// 加载环境变量
dotenv.config();

class CrawlerApplication {
  private crawlerService: CrawlerService;
  private queueProcessor: QueueProcessor;
  private schedulerService: SchedulerService;

  constructor() {
    this.crawlerService = new CrawlerService();
    this.queueProcessor = new QueueProcessor(this.crawlerService);
    this.schedulerService = new SchedulerService(this.crawlerService);
  }

  async start(): Promise<void> {
    try {
      logger.info('🚀 Starting Weubi Crawler Service...');

      // 初始化数据库连接
      logger.info('🔗 Connecting to database...');
      await initializeDatabase();

      // 启动爬虫服务
      logger.info('🕷️ Initializing crawler service...');
      await this.crawlerService.initialize();

      // 启动队列处理器
      logger.info('🔄 Starting queue processors...');
      await this.queueProcessor.start();

      // 调度服务已初始化，无需额外启动
      logger.info('⏰ Scheduler service initialized');

      logger.info('✅ Crawler service started successfully');
      logger.info(`🎯 Environment: ${process.env.NODE_ENV || 'development'}`);
      const availableEngines = await this.crawlerService.getAvailableEngines();
      logger.info(`🔧 Available engines: ${availableEngines.join(', ')}`);

      // 优雅关闭处理
      this.setupGracefulShutdown();

    } catch (error) {
      logger.error('❌ Failed to start crawler service:', error);
      process.exit(1);
    }
  }

  private setupGracefulShutdown(): void {
    const shutdown = async (signal: string) => {
      logger.info(`🛑 Received ${signal}, shutting down gracefully...`);

      try {
        // 停止接收新任务
        await this.queueProcessor.stop();
        logger.info('✅ Queue processor stopped');

        // 停止调度服务
        this.schedulerService.stopAll();
        logger.info('✅ Scheduler service stopped');

        // 清理爬虫服务资源
        await this.crawlerService.cleanup();
        logger.info('✅ Crawler service cleaned up');

        logger.info('✅ Graceful shutdown completed');
        process.exit(0);
      } catch (error) {
        logger.error('❌ Error during shutdown:', error);
        process.exit(1);
      }
    };

    process.on('SIGTERM', () => shutdown('SIGTERM'));
    process.on('SIGINT', () => shutdown('SIGINT'));

    // 处理未捕获的异常
    process.on('uncaughtException', (error) => {
      logger.error('❌ Uncaught Exception:', error);
      process.exit(1);
    });

    process.on('unhandledRejection', (reason, promise) => {
      logger.error('❌ Unhandled Rejection at:', promise, 'reason:', reason);
      process.exit(1);
    });
  }
}

// 启动应用
const app = new CrawlerApplication();
app.start().catch((error) => {
  logger.error('❌ Failed to start application:', error);
  process.exit(1);
});
